#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <cjson/cJSON.h>
#include "http.h"
#include "config.h"
#include "token.h"

//成功返回access token，失败返回NULL
char *get_access_token(const char *ak, const char *sk)
{
    char* token = NULL;

    //设置URL
    char* url = "https://aip.baidubce.com/oauth/2.0/token";
    char* form = NULL;
    asprintf(&form, "grant_type=client_credentials&client_id=%s&client_secret=%s&", ak, sk);

    //发送请求报文
    size_t size = strlen(form);
    char* response = post(url, NULL, form, &size);
    free(form);

    if (!response)
    {
        return NULL;
    }

    //解析响应报文
    cJSON* root = cJSON_ParseWithLength(response, size);
    free(response);

    if (!root)
    {
        // 解析错误
        const char *error_ptr = cJSON_GetErrorPtr();
        if (error_ptr != NULL)
        {
            fprintf(stderr, "Error before: %s\n", error_ptr);
        }
        return NULL;
    }

    cJSON* access_token = cJSON_GetObjectItem(root, "access_token");
    if (!access_token)
    {
        fprintf(stderr, "access_token attribute not found\n");
        cJSON_Delete(root);
        return NULL;
    }

    if (!cJSON_IsString(access_token))
    {
        fprintf(stderr, "access_token attribute format error\n");
        cJSON_Delete(root);
        return NULL;
    }

    token = strdup(access_token->valuestring);

    // 删除解析后对象占用的内存
    cJSON_Delete(root);

    return token;
}

#if 0
int main()
{
    struct cJSON* config = read_config("app.json");
    if (!config)
    {
        return EXIT_FAILURE;
    }

    struct cJSON* api_key = cJSON_GetObjectItem(config, "api_key");
    struct cJSON* secret_key = cJSON_GetObjectItem(config, "secret_key");
    if (!api_key || !secret_key)
    {
        fprintf(stderr, "api_key or secret_key not found in config file\n");
        cJSON_Delete(config);
        return EXIT_FAILURE;
    }

    char *token = get_access_token(api_key->valuestring, secret_key->valuestring);
    if (token) {
        printf("Access Token: %s\n", token);
        free(token); // 释放内存
    }

    cJSON_Delete(config);

    return 0;
}
# endif